package com.bzy.blp.shiro;

import java.util.Set;
import javax.annotation.Resource;

import com.bzy.blp.model.TSystemUserInfoDat;
import com.bzy.blp.service.ISystemUserManagerService;
import com.bzy.common.util.SerializationUtil;
import com.bzy.shiro.util.SessionUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class UserRealm extends AuthorizingRealm {

	@Resource
	private ISystemUserManagerService userManagerService;


	/**
     *
	 * 进行角色和权限验证，当配置 = roles[]时该方法会被调用
	 * @param principals
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "unused" })
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Session session = SecurityUtils.getSubject().getSession();
		String username = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		Set<String> roles = (Set<String>) SessionUtil.getUserRoles();
		Set<String> permissions = (Set<String>) SessionUtil.getUserPermissions();
		authorizationInfo.setRoles(roles);
		authorizationInfo.setStringPermissions(permissions);
		return authorizationInfo;
	}


	/**
	 * 执行SecurityUtils.getSubject().login()时候会调用到该方法，即（登录验证）
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		TSystemUserInfoDat user = userManagerService.queryUserByUserName(username);

		if (user == null) {
			throw new UnknownAccountException();// 没找到帐号
		}

		if (Boolean.TRUE.equals(user.getLocked())) {
			throw new LockedAccountException(); // 帐号锁定
		}

		if (user.getAccountStatus().intValue()==1) {
		    throw new DisabledAccountException(); // 账号禁用
        }

		// 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), // 用户名
				user.getPassword(), // 密码
				ByteSource.Util.bytes(user.getUserName() + user.getSalt()), // credentialsSalt=username+salt
				getName() // realm name
		);

		return authenticationInfo;
	}

	public static void main(String[] args) {
		String username = "admin";
		String password = "123456";
		ByteSource bytes = ByteSource.Util.bytes(username + password);
		System.out.println(bytes);

		String sss = "rO0ABXNyAClqYXZhLnV0aWwuY29uY3VycmVudC5hdG9taWMuQXRvbWljSW50ZWdlclY/XsyMbBaKAgABSQAFdmFsdWV4cgAQamF2YS5sYW5nLk51bWJlcoaslR0LlOCLAgAAeHAAAAAB";
        Object deserialize = SerializationUtil.deserialize(Base64.decode(sss));
        System.out.println(deserialize);
    }
}
